package com.yiwei.zxp.fragment;

import android.content.Intent;
import android.graphics.Color;
import android.graphics.Typeface;
import android.os.Bundle;
import android.support.v4.widget.NestedScrollView;
import android.support.v4.widget.SwipeRefreshLayout;
import android.text.Spanned;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.allen.library.CircleImageView;
import com.allen.library.SuperButton;
import com.bumptech.glide.Glide;
import com.yiwei.zxp.BussinessMainActivity;
import com.yiwei.zxp.MainActivity;
import com.yiwei.zxp.R;
import com.yiwei.zxp.activity.AccountSecurityActivity;
import com.yiwei.zxp.activity.BankListAllActivity;
import com.yiwei.zxp.activity.BrowseFootActivity;
import com.yiwei.zxp.activity.BussinessMsgTotalActivity;
import com.yiwei.zxp.activity.BuyerOrderActivity;
import com.yiwei.zxp.activity.InviteActivity;
import com.yiwei.zxp.activity.LoginNewActivity;
import com.yiwei.zxp.activity.MyAddressActivity;
import com.yiwei.zxp.activity.MyCollectionActivity;
import com.yiwei.zxp.activity.MyCommentActivity;
import com.yiwei.zxp.activity.MyCommissionActivity;
import com.yiwei.zxp.activity.PersonalCenterActivity;
import com.yiwei.zxp.activity.SecurityHasSetActivity;
import com.yiwei.zxp.activity.SettingActivity;
import com.yiwei.zxp.activity.WechatChatActivity;
import com.yiwei.zxp.api.Api;
import com.yiwei.zxp.api.model.UserBuyIndexModel;
import com.yiwei.zxp.api.model.UserInfoModel;
import com.yiwei.zxp.constant.UserInfoGlobal;
import com.yiwei.zxp.event.BussinessSetCodeEvent;
import com.yiwei.zxp.event.BuyerSetCodeEvent;
import com.yiwei.zxp.event.LoginSuccessEvent;
import com.yiwei.zxp.event.LogoutEvent;
import com.yiwei.zxp.event.MsgTotalEvent;
import com.yiwei.zxp.event.UserInfoRequestEvent;
import com.yiwei.zxp.util.Network;
import com.yiwei.zxp.util.RxLifeUtil;
import com.yiwei.zxp.util.Spans;
import com.yiwei.zxp.util.ToastUtil;
import com.yiwei.zxp.util.UI;
import com.yiwei.zxp.util.Util;
import com.yiwei.zxp.view.BottomIconText;
import com.yiwei.zxp.view.V19RelativeLayout;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;

/**
 * Created by xsooy-pc on 18-5-15.
 */

public class BuyerMyFragment extends BaseFragment implements NestedScrollView.OnScrollChangeListener {
    @BindView(R.id.view_top)
    View viewTop;
    @BindView(R.id.txt_type)
    TextView txtType;
    @BindView(R.id.img_icon)
    CircleImageView imgIcon;
    @BindView(R.id.layout_top)
    LinearLayout layoutTop;
    @BindView(R.id.btn_my_collection)
    TextView btnMyCollection;
    @BindView(R.id.btn_liulan)
    TextView btnLiulan;
    @BindView(R.id.btn_my_coupon)
    TextView btnMyCoupon;
    @BindView(R.id.btn_my_order)
    LinearLayout btnMyOrder;
    @BindView(R.id.btn_one)
    BottomIconText btnOne;
    @BindView(R.id.btn_two)
    BottomIconText btnTwo;
    @BindView(R.id.btn_three)
    BottomIconText btnThree;
    @BindView(R.id.btn_four)
    BottomIconText btnFour;
    @BindView(R.id.btn_five)
    BottomIconText btnFive;
    @BindView(R.id.btn_my_commission)
    BottomIconText btnMyCommission;
    @BindView(R.id.btn_my_bankcard)
    BottomIconText btnMyBankcard;
    @BindView(R.id.btn_my_chatcenter)
    BottomIconText btnMyChatcenter;
    @BindView(R.id.btn_my_share_money)
    LinearLayout btnMyShareMoney;
    @BindView(R.id.refresh)
    SwipeRefreshLayout refresh;
    Unbinder unbinder;
    @BindView(R.id.txt_msg_number)
    TextView txtMsgNumber;
    @BindView(R.id.txt_user)
    TextView txtUser;
    @BindView(R.id.view_one)
    View viewOne;
    @BindView(R.id.txt_one_number)
    TextView txtOneNumber;
    @BindView(R.id.view_two)
    View viewTwo;
    @BindView(R.id.txt_two_number)
    TextView txtTwoNumber;
    @BindView(R.id.view_three)
    View viewThree;
    @BindView(R.id.txt_three_number)
    TextView txtThreeNumber;
    @BindView(R.id.view_four)
    View viewFour;
    @BindView(R.id.txt_four_number)
    TextView txtFourNumber;
    @BindView(R.id.view_five)
    View viewFive;
    @BindView(R.id.txt_five_number)
    TextView txtFiveNumber;
    @BindView(R.id.btn_msg)
    ImageView btnMsg;
    @BindView(R.id.btn_setting)
    ImageView btnSetting;
    @BindView(R.id.btn_invite_code)
    SuperButton btnInviteCode;
    @BindView(R.id.btn_invite)
    ImageView btnInvite;
    @BindView(R.id.btn_my_address)
    BottomIconText btnMyAddress;
    @BindView(R.id.btn_my_security)
    BottomIconText btnMySecurity;
    @BindView(R.id.txt_invite_code)
    TextView txtInviteCode;
    @BindView(R.id.toolbar)
    V19RelativeLayout toolbar;
    @BindView(R.id.scrollView)
    NestedScrollView scrollView;
    private int textSize36;
    private int textSize24;
    private boolean isLogin = false;
    private float headerHeight;
    private float minHeaderHeight;

    @Override
    protected int setLayoutId() {
        return R.layout.fragment_buyer_my;
    }

    @Override
    protected void initView() {
        textSize36 = getResources().getDimensionPixelSize(R.dimen.x36);
        textSize24 = getResources().getDimensionPixelSize(R.dimen.x24);
        headerHeight = getResources().getDimensionPixelSize(R.dimen.y300);
        minHeaderHeight = getResources().getDimension(R.dimen.y98);
        scrollView.setOnScrollChangeListener(this);
        refresh.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                if (UserInfoGlobal.isLogin()) {
                    ((BussinessMainActivity) getActivity()).getUser();
                    getUserBuyIndex();
                    ((BussinessMainActivity) getActivity()).getMsgTotal();
                } else {
                    ToastUtil.makeText(getContext(), "请先登录");
                    refresh.setRefreshing(false);
                    txtUser.setText("登录");
                    txtInviteCode.setVisibility(View.GONE);
                    btnInviteCode.setVisibility(View.GONE);
                    txtMsgNumber.setVisibility(View.GONE);
                }

            }
        });
        EventBus.getDefault().register(this);
//        ((BussinessMainActivity) getActivity()).getUser();
    }

    @Override
    public void onResume() {
        super.onResume();
        getUserBuyIndex();

        if (!UserInfoGlobal.isLogin()) {
            txtMsgNumber.setVisibility(View.GONE);
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEvent(UserInfoRequestEvent event) {
        if (event.isLogin) {
            setUserData(event.item);
        } else {
            txtUser.setText("登录");
            txtInviteCode.setVisibility(View.GONE);
            btnInviteCode.setVisibility(View.GONE);
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEvent(BussinessSetCodeEvent event) {
        ((BussinessMainActivity) getActivity()).getUser();
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEvent(MsgTotalEvent event) {
        if (event.totalCount == 0) {
            if (txtMsgNumber != null)
                txtMsgNumber.setVisibility(View.GONE);
        } else {
            if (txtMsgNumber != null) {
                txtMsgNumber.setVisibility(View.VISIBLE);
                txtMsgNumber.setText(event.totalCount + "");
            }
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEvent(LoginSuccessEvent event) {
        isLogin = true;
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEvent(LogoutEvent event) {
        txtUser.setText("登录");
        txtInviteCode.setVisibility(View.GONE);
        btnInviteCode.setVisibility(View.GONE);
        imgIcon.setImageResource(R.mipmap.img_my_default);
    }

    private Spanned setContentInfo(String top, String bottom) {
        return Spans.with(this).font(TextUtils.isEmpty(top) ? "" : top, textSize36, 0xff000000).style(Typeface.BOLD).
                font("\n" + bottom, textSize24, 0xff999999).
                build();
    }


    @Override
    protected void lazyLoad() {

    }

//    public void getMsgTotal() {
//        if (!Network.checkNetwork(getContext())) {
//            ToastUtil.show(getContext(), "网络连接失败");
//            return;
//        }
//        Api.api_service.getMessageCenter().compose(RxLifeUtil.checkOn(this)).
//                doFinally(() -> {
//                    try {
//
//                    } catch (NullPointerException e) {
//
//                    }
//                }).
//                subscribe(result -> {
//
//                    if (result.datas.totalCount == 0) {
//                        txtMsgNumber.setVisibility(View.GONE);
//                    } else {
//                        txtMsgNumber.setVisibility(View.VISIBLE);
//                        txtMsgNumber.setText(result.datas.totalCount + "");
//                    }
//                });
//    }

//    public void getUser() {
//        if (!Network.checkNetwork(getContext())) {
//            ToastUtil.show(getContext(), "网络连接失败");
//            return;
//        }
//
//        if (refresh != null) {
//            refresh.setRefreshing(true);
//        }
//
//        Api.api_service.getUserInfo().compose(RxLifeUtil.NocheckOn(this)).
//                doFinally(() -> {
//                    try {
//                        refresh.setRefreshing(false);
//                    } catch (NullPointerException e) {
//
//                    }
//                }).
//                subscribe(result -> {
//
//                    if (result.code.equals("00")) {
//                        setUserData(result.datas);
//                    } else {
//                        txtUser.setText("登录");
//                        txtInviteCode.setVisibility(View.GONE);
//                        btnInviteCode.setVisibility(View.GONE);
//                    }
//                });
//    }

    public void getUserBuyIndex() {
        if (!Network.checkNetwork(getContext())) {
            ToastUtil.show(getContext(), "网络连接失败");
            return;
        }

        if (refresh != null) {
            refresh.setRefreshing(true);
        }

        Api.api_service.getUserBuyIndex().compose(RxLifeUtil.checkOn(this)).
                doFinally(() -> {
                    try {
                        refresh.setRefreshing(false);
                    } catch (NullPointerException e) {

                    }
                }).
                subscribe(result -> {

                    setIndexData(result.datas);
                });
    }

    public void getInviteCode() {
        if (!Network.checkNetwork(getContext())) {
            ToastUtil.show(getContext(), "网络连接失败");
            return;
        }

        refresh.setRefreshing(true);
        Api.api_service.getSetInvitecode().compose(RxLifeUtil.checkOn(getContext())).
                doFinally(() -> {
                    try {
                        refresh.setRefreshing(false);
                    } catch (NullPointerException e) {

                    }
                }).
                subscribe(result -> {
                    ToastUtil.makeText(getContext(), "邀请码生成成功");
                    UserInfoGlobal.setInviteCode(result.datas.invite_code);
//                    getUser();
                    EventBus.getDefault().post(new BuyerSetCodeEvent());
                    txtInviteCode.setText("我的邀请码：" + result.datas.invite_code);
                    txtInviteCode.setVisibility(View.VISIBLE);
                    btnInviteCode.setVisibility(View.GONE);
                });
    }

    private void setIndexData(UserBuyIndexModel.DatasBean item) {
        if (item == null) {
            return;
        }
        btnMyCollection.setText(setContentInfo(item.base.favorites, "我的收藏"));
        btnLiulan.setText(setContentInfo(item.base.browse_history, "浏览足迹"));
        btnMyCoupon.setText(setContentInfo(item.base.coupon, "优惠券"));
        UserBuyIndexModel.DatasBean.OrdersBean data = item.orders;
        if (data.wait_pay == 0) {
            txtOneNumber.setVisibility(View.GONE);
        } else {
            txtOneNumber.setVisibility(View.VISIBLE);
            txtOneNumber.setText(data.wait_pay + "");
        }

        if (data.wait_send == 0) {
            txtTwoNumber.setVisibility(View.GONE);
        } else {
            txtTwoNumber.setVisibility(View.VISIBLE);
            txtTwoNumber.setText(data.wait_send + "");
        }

        if (data.wait_get == 0) {
            txtThreeNumber.setVisibility(View.GONE);
        } else {
            txtThreeNumber.setVisibility(View.VISIBLE);
            txtThreeNumber.setText(data.wait_get + "");
        }

        if (data.wait_comm == 0) {
            txtFourNumber.setVisibility(View.GONE);
        } else {
            txtFourNumber.setVisibility(View.VISIBLE);
            txtFourNumber.setText(data.wait_comm + "");
        }

        if (data.after == 0) {
            txtFiveNumber.setVisibility(View.GONE);
        } else {
            txtFiveNumber.setVisibility(View.VISIBLE);
            txtFiveNumber.setText(data.after + "");
        }
    }

    private void setUserData(UserInfoModel.DatasBean item) {
        if (item == null) {
            return;
        }
        UserInfoGlobal.saveUserInfo(item);
        if (!TextUtils.isEmpty(item.username)) {
            txtUser.setText(item.username);
        } else if (!TextUtils.isEmpty(item.phone)) {
            txtUser.setText(item.phone);
        }
        if (TextUtils.isEmpty(item.invite_code)) {
            txtInviteCode.setVisibility(View.GONE);
            btnInviteCode.setVisibility(View.VISIBLE);
        } else {
            txtInviteCode.setText("我的邀请码：" + item.invite_code);
            txtInviteCode.setVisibility(View.VISIBLE);
            btnInviteCode.setVisibility(View.GONE);
        }
        Glide.with(this).load(item.icon).asBitmap().error(R.mipmap.img_my_default).into(imgIcon);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        // TODO: inflate a fragment view
        View rootView = super.onCreateView(inflater, container, savedInstanceState);
        unbinder = ButterKnife.bind(this, rootView);
        return rootView;
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
//        unbinder.unbind();
        EventBus.getDefault().unregister(this);
    }

    @OnClick({R.id.btn_my_comment, R.id.btn_my_invite, R.id.btn_invite_code, R.id.btn_invite, R.id.btn_msg, R.id.btn_my_address, R.id.btn_my_security, R.id.btn_setting, R.id.txt_type, R.id.img_icon, R.id.btn_my_collection, R.id.btn_liulan, R.id.btn_my_coupon, R.id.btn_my_order, R.id.btn_one, R.id.btn_two, R.id.btn_three, R.id.btn_four, R.id.btn_five, R.id.btn_my_commission, R.id.btn_my_bankcard, R.id.btn_my_chatcenter, R.id.btn_my_share_money})
    public void onViewClicked(View view) {
        if (UI.isFastClick()) {
            return;
        }
        if (!UserInfoGlobal.isLogin()) {
            Util.startActivity(getActivity(), LoginNewActivity.class);
            return;
        }
        switch (view.getId()) {
            case R.id.btn_my_comment:
                Util.startActivity(getContext(), MyCommentActivity.class);
                break;
            case R.id.btn_my_invite:
                Util.startActivity(getContext(), InviteActivity.class);
                break;
            case R.id.btn_invite_code:
                getInviteCode();
                break;
            case R.id.btn_invite:
                Util.startActivity(getContext(), InviteActivity.class);
                break;
            case R.id.img_icon:
                if (!UserInfoGlobal.isLogin()) {
                    Util.startActivity(getActivity(), LoginNewActivity.class);
                } else {
                    Util.startActivity(getActivity(), PersonalCenterActivity.class);
                }
//                UserInfoGlobal.logout();
//                Util.startActivity(getActivity(), LoginNewActivity.class);
                break;
            case R.id.btn_msg:
                Util.startActivity(getActivity(), BussinessMsgTotalActivity.class);
                break;
            case R.id.btn_setting:
                Util.startActivity(getActivity(), SettingActivity.class);
                break;
            case R.id.btn_my_security:
                if (!UserInfoGlobal.isLogin()) {
                    ToastUtil.makeText(getContext(), "请先登录");
                    return;
                }
                if (UserInfoGlobal.getIssetPayPass()) {
                    Util.startActivity(getActivity(), SecurityHasSetActivity.class);
                } else {
                    Util.startActivity(getActivity(), AccountSecurityActivity.class);
                }

                break;
            case R.id.btn_my_address:
                Util.startActivity(getActivity(), MyAddressActivity.class);
                break;
            case R.id.txt_type:
                ((BussinessMainActivity) getActivity()).changePage(1);
                break;
            case R.id.btn_my_collection:
                Util.startActivity(getActivity(), MyCollectionActivity.class);
                break;
            case R.id.btn_liulan:
                Util.startActivity(getActivity(), BrowseFootActivity.class);
//                ToastUtil.makeTipsText("账号不存在");
                break;
            case R.id.btn_my_coupon:
                break;
            case R.id.btn_my_order:
                Util.startActivity(getActivity(), BuyerOrderActivity.class);
                break;
            case R.id.btn_one:
                Intent intent = new Intent(getActivity(), BuyerOrderActivity.class);
                intent.putExtra("poi", 1);
                startActivity(intent);
                getActivity().overridePendingTransition(R.anim.right_enter, R.anim.left_out);
                break;
            case R.id.btn_two:
                Intent intent1 = new Intent(getActivity(), BuyerOrderActivity.class);
                intent1.putExtra("poi", 2);
                startActivity(intent1);
                getActivity().overridePendingTransition(R.anim.right_enter, R.anim.left_out);
                break;
            case R.id.btn_three:
                Intent intent2 = new Intent(getActivity(), BuyerOrderActivity.class);
                intent2.putExtra("poi", 3);
                startActivity(intent2);
                getActivity().overridePendingTransition(R.anim.right_enter, R.anim.left_out);
                break;
            case R.id.btn_four:
                Intent intent3 = new Intent(getActivity(), BuyerOrderActivity.class);
                intent3.putExtra("poi", 4);
                startActivity(intent3);
                getActivity().overridePendingTransition(R.anim.right_enter, R.anim.left_out);
                break;
            case R.id.btn_five:
                Intent intent4 = new Intent(getActivity(), BuyerOrderActivity.class);
                intent4.putExtra("poi", 4);
                startActivity(intent4);
                getActivity().overridePendingTransition(R.anim.right_enter, R.anim.left_out);
                break;
            case R.id.btn_my_commission:
                Util.startActivity(getActivity(), MyCommissionActivity.class);
                break;
            case R.id.btn_my_bankcard:
                Util.startActivity(getActivity(), BankListAllActivity.class);
                break;
            case R.id.btn_my_chatcenter:
                Util.startActivity(getActivity(), WechatChatActivity.class);
                break;
            case R.id.btn_my_share_money:
                Util.startActivity(getActivity(), MainActivity.class);
                break;
        }
    }

    @Override
    public void onScrollChange(NestedScrollView v, int x, int y, int oldScrollX, int oldScrollY) {
        //Y轴偏移量
        float scrollY = scrollView.getScrollY();
//        e3483d
        //变化率
        float headerBarOffsetY = headerHeight - minHeaderHeight;//Toolbar与header高度的差值
        float offset = 1 - Math.max((headerBarOffsetY - scrollY) / headerBarOffsetY, 0f);

        if (scrollY >= headerHeight) {
            toolbar.setBackgroundColor(Color.argb(255, 255, 0, 48));
        } else {

            if (scrollY == 0) {

            } else {
                toolbar.setBackgroundColor(Color.argb((int) (offset * 255), 255, 0, 48));
            }
        }
    }
}
